<template>
	<view>
		<custom-header title="注册" />
		<!-- 步骤 -->
		<view class="step_bar_wrap">
			<view class="step_bar">
				<view 
					class="list"
					:class="{'active':step == item.id}"
					v-for="(item,index) in stepList" 
					:key="index">
						<view class="text">{{ item.name }}</view>
						<view class="icon">
							<image src="/static/login/check.png" mode="" v-if="step == item.id"></image>
							<image src="/static/common/no_check.png" mode="" v-else></image>
						</view>
				</view>
			</view>
		</view>
		<!-- 填写信息 -->
		<scroll-view
			:scroll-y="true" 
			scroll-with-animation
			:style="{height:'calc(100vh - 128rpx - 145rpx - '+statusBarHeight+'px)'}"
			class="scroll_content_wrap">
				<!-- 入驻商家信息 -->
				<view class="_wrap" v-if="step == 1">
					<view class="form_wrap">
						<view class="form_item">
							<view class="label">店铺类别<text class="required">*</text></view>
							<view class="value_select" @click="isShowShopType = true">
								<view class="text">
									{{form.shopType || '请选择店铺类型'}}
								</view>
								<view class="right_icon">
									<image src="/static/common/right.png" mode=""></image>
								</view>
							</view>
						</view>
						<view class="form_item">
							<view class="label">卖家头像<text class="required">*</text></view>
							<view class="value_headPortrait">
								<custom-upload-tx v-model="form.tx"></custom-upload-tx>
							</view>
						</view>
						<view class="form_item">
							<view class="label">卖家名称<text class="required">*</text></view>
							<view class="value">
								<input
									type="text"
									placeholder="请填写卖家名称（不超过6个字符）"
									v-model="form.shopName"
									@input="handleBtnBisabled"
									:maxlength="6">
							</view>
						</view>
						<view class="form_item">
							<view class="label">联系人姓名<text class="required">*</text></view>
							<view class="value">
								<input
									type="text"
									placeholder="请填写联系人姓名"
									v-model="form.contactName"
									@input="handleBtnBisabled">
							</view>
						</view>
						<view class="form_item">
							<view class="label">联系人电话<text class="required">*</text></view>
							<view class="value">
								<input
									type="number"
									placeholder="请输入"
									v-model="form.contactPhone"
									@input="handleBtnBisabled">
							</view>
						</view>
						<view class="form_item">
							<view class="label">地区<text class="required">*</text></view>
							<view class="value">
								<picker mode='region' :value="value" @change="handleChangeArea">
									<view style="display: flex;align-items: center;">
										<text v-if="form.addressCn" style="color: #333;padding-right: 10rpx;">
											{{ form.addressCn }}
										</text>
										<text v-else style="color: #999;padding-right: 10rpx;">请选择</text>
										<image src="/static/common/right.png" style="width: 10rpx;height: 20rpx;"></image>
									</view>
								</picker>
							</view>
						</view>
						<view class="form_item">
							<view class="label">详细地址<text class="required">*</text></view>
							<view class="value">
								<input
									type="text"
									placeholder="请输入详细地址"
									v-model="form.address"
									@input="handleBtnBisabled">
							</view>
						</view>
						<view class="form_item_textarea">
							<view class="label">卖家简介</view>
							<view class="value">
								<up-textarea
									v-model="form.introduction" 
									placeholder="主要销售哪些品种，是基地还是包花厂，来自哪个产区等等，让客户了解你的优势。"
									border="none"
									style="padding:25rpx;background: #F8F8F8;border-radius: 20rpx;"
									placeholderStyle="font-size:24rpx;color:#AAAAAA">
								</up-textarea>
							</view>
						</view>
						<view class="form_item_textarea">
							<view class="label">卖家实力展示</view>
							<view class="value">
								<custom-upload v-model="form.imageList" :maxCount="1"></custom-upload>
							</view>
						</view>
						
						
					</view>
				</view>
				<!-- 验证手机号 -->
				<view class="_wrap" v-if="step == 2">
					<view class="phoneNumber_wrap">
						<view class="title">验证手机号码</view>
						<view class="hint">
							<view class="plaint_icon">
								<image src="/static/login/plaint.png" mode=""></image>
							</view>
							<view class="text">现阶段仅限云南产地的供应商入驻</view>
						</view>
						<view class="phone">
							<view class="icon">
								<image src="/static/login/phone_icon1.png" mode=""></image>
							</view>
							<view class="input">
								<input type="number" v-model="form.phone" @input="handleBtnBisabled" placeholder="请输入手机号码" />
							</view>
							<view class="right" style="background: transparent;"></view>
						</view>
						<view class="code">
							<view class="icon">
								<image src="/static/login/code_icon1.png" mode=""></image>
							</view>
							<view class="input">
								<input type="number" v-model="form.code" @input="handleBtnBisabled" placeholder="请输入验证码" />
							</view>
							<view
								class="right"
								hover-class="confirm_hover"
								:hover-stay-time="200"
								@click="getVerificationCode">
									{{ buttonText }}
							</view>
						</view>
						<view class="read"  @click="checked = !checked">
							<view class="icon">
								<image src="/static/common/check.png" mode="" v-if="checked"></image>
								<image src="/static/common/no_check.png" mode="" v-else></image>
							</view>
							<view class="text">
								勾选代表您已阅读并同意
								<text @click.stop="handleShowNotice">《卖家入驻协议》</text>
								<text @click.stop="handleShowNotice">《隐私政策》</text>
								<text @click.stop="handleShowNotice">《隐私政策》</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 完成注册 -->
				<view class="_wrap" v-if="step == 3">
					<view class="success_wrap">
						<view class="success">
							<view class="icon">
								<image src="/static/common/success.png" mode=""></image>
							</view>
							<view class="text">注册成功</view>
						</view>
						<!-- <view class="success">
							<view class="icon">
								<image src="/static/common/fail.png" mode=""></image>
							</view>
							<view class="text">注册失败</view>
						</view> -->
					</view>
				</view>
		</scroll-view>
		<!-- 底部按钮 -->
		<view class="footer_btn_wrap">
			<view class="btn_wrap">
				<button
					size="default" 
					type="default" 
					class="btn confirm" 
					hover-class="confirm_hover" 
					:hover-stay-time="200" 
					@click="handleNext"
					:class="{'btn_disable':btnBisabled && step != 3}"
					:loading="btnLoading">
						{{ step == 3?'去登录':'下一步' }}
				</button>
			</view>
		</view>
		<!-- 自定义消息弹出层 -->
		<custom-popup
			:show="isShowToast" 
			:config="popupConfig"
			@confirm="handleMsgConfirm" />
		<!-- 店铺类别 -->
		<custom-select 
			:show="isShowShopType" 
			:datas="shopTypeList" 
			@confirm="handleTypeConfirm"
			@close="isShowShopType = false"></custom-select>
	</view>
</template>

<script setup>
	import { computed, ref , onMounted, onUnmounted} from 'vue';
	import { useStore } from 'vuex';
	import { isvalidPhoneNumber } from '../../utils/validate.js'
	import suppApi from '@/api/supplier'
	import authApi from '@/api/auth'

	const store = useStore();
	const statusBarHeight = computed(()=>{
		return store.getters.statusBarHeight;
	});
	
	// 消息弹出层
	const isShowToast = ref(false)
	const popupConfig = ref({})
	const handleMsgConfirm = (data)=>{
		isShowToast.value = false
	}
	
	const form = ref({})
	
	const step = ref(1)
	const stepList = ref([
		{ id:1,name:'入驻商家信息' },
		{ id:2,name:'验证手机号' },
		{ id:3,name:'完成注册' },
	])
	
	// 选择地址
	const value = ref([])
	const handleChangeArea = (e)=>{
		try {
			const { value, code } = e.detail
			form.value.addressCn = `${value[0]},${value[1]},${value[2]}`
			form.value.addressCode = `${code[0]},${code[1]},${code[2]}`
			handleBtnBisabled()
		} catch (error) {
			console.error("地区选择处理异常:", error)
			uni.showToast({
				title: '地区选择异常，请重试',
				icon: 'none'
			})
		}
	}
	// 选择类别
	const isShowShopType = ref(false)
	const shopTypeList = ref([])
	const shopCategoryData = ref([]) // 存储接口返回的原始数据

	// 获取店铺类别列表
	const getCategoryList = async () => {
		try {
			const response = await suppApi.getCategoryList()
			shopCategoryData.value = response
			shopTypeList.value = response.map(item => item.name)
		} catch (error) {
			console.error('获取店铺类别失败:', error)
			popupConfig.value.message = '获取店铺类别失败，请检查网络连接'
			isShowToast.value = true
		}
	}

	const handleTypeConfirm = (value)=>{
		// 根据选中的名称找到对应的ID
		const selectedCategory = shopCategoryData.value.find(item => item.name === value)
		form.value.shopType = value
		if (selectedCategory) {
			form.value.shopTypeId = selectedCategory.id
		}
		handleBtnBisabled()
	}

	/**
	 * 从图片列表中提取URL字符串数组
	 * @param {Array} imageList 图片对象数组
	 * @returns {Array} URL字符串数组
	 */
	const extractImageUrls = (imageList) => {
		console.log('原始图片数据:', imageList)

		if (!imageList || !Array.isArray(imageList)) {
			console.log('图片列表为空或不是数组')
			return []
		}

		const urls = imageList.map(item => {
			if (typeof item === 'object' && item !== null) {
				return item.url || item.tempFilePath || ''
			}
			return ''
		}).filter(url => url) 

		console.log('提取的URL数组:', urls)
		return urls
	}

	/**
	 * 提交店铺注册
	 * @returns {Promise} 注册结果
	 */
	const submitShopRegister = async () => {
		btnLoading.value = true
		// 构造注册数据
		const registerData = {
			shopName: form.value.shopName, // 店铺名称
			name: form.value.contactName, // 联系人姓名
			phone: form.value.contactPhone, // 联系人手机号
			categoryId: form.value.shopTypeId, // 商品分类ID
			addressCode: form.value.addressCode, // 省市区编码
			addressCn: form.value.addressCn, // 省市区名称
			address: form.value.address, // 详细地址
			blurb: form.value.introduction, // 简介
			avatarId: form.value.tx, // 店铺头像ID
			resourceIdList: extractImageUrls(form.value.imageList), // 店铺实力展示
			smsCode: form.value.code // 手机验证码
		}

		console.log('提交注册数据:', registerData)

		const response = await suppApi.registerShop(registerData)
		console.log("11",response)
		setTimeout(()=>{
			btnLoading.value = false
			step.value = 3
		}, 1500)
		return Promise.resolve(response)
	}
	
	
	
	// 获取验证码 倒计时
	const isCounting = ref(false)
	const countdown = ref(0)
	const totalTime = ref(60)
	const copySuccess = ref(false)
	// 计算按钮文本
	const buttonText = computed(() => {
	  if (isCounting.value) {
		return `${countdown.value}S`
	  }
	  return countdown.value === 0 ? '重新获取' : '获取验证码'
	})
	
	// 获取验证码
	const getVerificationCode = async () => {
	  if (isCounting.value) return
	  if (!form.value.phone) {
		popupConfig.value.message = '请输入手机号码'
		isShowToast.value = true
		return
	  }
	  if (!isvalidPhoneNumber(form.value.phone)) {
	  		popupConfig.value.message = '手机号码格式不正确'
	  		isShowToast.value = true
	  		return
	  }
	  // 这里可以添加实际的API请求

		uni.showLoading({
			title: '发送中...'
		});

		const res = await suppApi.getShopRegisterCode(form.value.phone)
		uni.hideLoading()
		uni.showToast({
			title: '验证码发送成功',
			icon: 'success'
		})

		// 开始倒计时
		startCountdown()
	
	}
	// 开始倒计时
	const startCountdown = () => {
	  isCounting.value = true
	  countdown.value = totalTime.value
	  // 设置定时器
	  const timer = setInterval(() => {
		countdown.value--
		if (countdown.value <= 0) {
		  clearInterval(timer)
		  isCounting.value = false
		}
	  }, 1000)
	  // 存储定时器以便清理
	  timerRef.value = timer
	}
	// 存储定时器引用
	const timerRef = ref(null)
	
	// 组件卸载时清除定时器
	onUnmounted(() => {
	  if (timerRef.value) {
		clearInterval(timerRef.value)
	  }
	})

	// 页面加载时获取店铺类别数据
	onMounted(() => {
		getCategoryList()
	})
	
	
	// 同意阅读
	const checked = ref(false)
	const handleShowNotice = ()=>{}
	
	
	// 判断是否可点击按钮
	const btnBisabled = ref(true)
	const handleBtnBisabled = ()=>{
		console.log('表单数据:', form.value)
		if(step.value == 1){
			// 第一步验证
			if(!form.value.shopType){
				return btnBisabled.value = true;
			}
			if(!form.value.shopName){
				return btnBisabled.value = true;
			}
			if(!form.value.contactName){
				return btnBisabled.value = true;
			}
			if(!form.value.contactPhone){
				return btnBisabled.value = true;
			}
			if(!form.value.addressCn){
				return btnBisabled.value = true;
			}
			if(!form.value.address){
				return btnBisabled.value = true;
			}
		}else if(step.value == 2){
			// 第二步验证
			if(!form.value.phone){
				return btnBisabled.value = true;
			}
			if(!form.value.code){
				return btnBisabled.value = true;
			}
		}
		btnBisabled.value = false
	}
	
	
	// 下一步/去登录
	const btnLoading = ref(false)
	const handleNext = async ()=>{
		
		if((btnBisabled.value || btnLoading.value) && step.value != 3)return;
		
		if(step.value == 1){
			step.value = 2
		}
		else if(step.value == 2){
			// 调用店铺注册方法
			await submitShopRegister()
		}
		else if(step.value == 3){
			uni.reLaunch({ url:'/pages/login/login' })
		}
		
	}
</script>

<style lang="scss">
	.step_bar_wrap{
		margin: 20rpx;
	}
	.step_bar{
		height: 100rpx;
		padding: 0 30rpx;
		border-radius: 20rpx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.list{
			display: flex;
			align-items: center;
			.text{
				font-size: 24rpx;
				color: #333;
			}
			.icon{
				width: 24rpx;
				height: 24rpx;
				margin-left: 10rpx;
				display: flex;
			}
			&::after{
				content: '';
				display: block;
				width: 59rpx;
				height: 2rpx;
				background: url('https://goods-1312936761.cos.ap-chongqing.myqcloud.com/applet/supplier/login/border.png');
				background-size: contain;
				margin-left: 18rpx;
			}
			&:last-child{
				&::after{
					display: none;
				}
			}
			&.active{
				.text{
					color: #00AD82;
				}
			}
		}
	}
	._wrap{
		padding:0 20rpx;
	}
	.form_wrap{
		border-radius: 20rpx;
		background: #FFFFFF;
		padding: 0 25rpx;
		.label{
			font-size: 24rpx;
			color: #333333;
			.required{
				color: #F70707;
			}
		}
		.form_item{
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 25rpx 0;
			border-top: 1px solid #F0F0F0;
			&:first-child{
				border: 0;
			}
			.value_select{
				display: flex;
				align-items: center;
				color: #999;
				font-size: 24rpx;
				.right_icon{
					width: 10rpx;
					height: 20rpx;
					display: flex;
					margin-left: 10rpx;
				}
				&.isHave{
					color: #666;
				}
			}
			.value{
				color: #666;
				font-size: 24rpx;
			}
		}
		.form_item_textarea{
			padding: 25rpx 0;
			border-top: 1px solid #F0F0F0;
			.value{
				padding-top: 25rpx;
			}
		}
	}
	.input-placeholder{
		font-size: 24rpx;
		color: #999;
		text-align: right;
	}
	input {
		font-size:24rpx;
		color: #666;
		text-align: right;
		width: 375rpx;
	}
	.u-textarea__field{
		font-size:24rpx !important;
	}
	.phoneNumber_wrap{
		border-radius: 20rpx;
		background: #FFFFFF;
		padding: 0 30rpx 380rpx;
		.title{
			font-size: 40rpx;
			font-weight: bold;
			color: #333;
			text-align: center;
			padding-top: 60rpx;
		}
		.hint{
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			color: #C60C0C;
			padding-top: 20rpx;
			.plaint_icon{
				width: 24rpx;
				height: 24rpx;
				display: flex;
				margin-right: 10rpx;
			}
		}
		.phone,.code{
			height: 88rpx;
			border-radius: 99rpx;
			background: #F8F8F8;
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			padding:0 25rpx;
			margin-top: 30rpx;
			.icon{
				width: 32rpx;
				height: 32rpx;
				display: flex;
			}
			.input{
				flex: 1;
				padding-left: 20rpx;
				.input-placeholder{
					text-align: left;
				}
				input{
					width: 100%;
					text-align: left;
				}
			}
			.right{
				// width: 200rpx;
				// color: #F5564D;
				// text-align: center;
				width: 140rpx;
				height: 52rpx;
				line-height: 52rpx;
				text-align: center;
				border-radius: 81rpx;
				background: #F5564D;
				color: #fff;
				font-size: 24rpx;
			}
		}
		.phone{
			margin-top: 100rpx;
		}
		.read{
			display: flex;
			justify-content: center;
			align-items: center;
			padding:30rpx 0 20rpx;
			.icon{
				width: 24rpx;
				height: 24rpx;
				display: flex;
			}
			.text{
				font-size: 20rpx;
				color: #bbb;
				padding-left: 10rpx;
				text{
					color: #F5564D;
				}
			}
		}
	}
	.success_wrap{
		border-radius: 20rpx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 800rpx;
		.success{
			.icon{
				width: 128rpx;
				height: 128rpx;
			}
			.text{
				font-size: 36rpx;
				color: #333;
				padding-top: 40rpx;
			}
		}
	}
</style>
